' PicBasic Pro program to read and write to I2C slave
'
' Writes a 1-byte offset value, pauses, then reads an 8
' character string from the slave. Expects to find the
' ADC conversion value (- offset) in the 6th position of
' the string.
 
 
' Define LCD registers and bits
DEFINE  LCD_DREG        PORTD
DEFINE  LCD_DBIT        4
DEFINE  LCD_RSREG       PORTE
DEFINE  LCD_RSBIT       0
DEFINE  LCD_EREG        PORTE
DEFINE  LCD_EBIT        1

DEFINE  I2C_HOLD        1

SCL     VAR     PORTC.3				' Clock pin
SDA     VAR     PORTC.4				' Data pin
a		VAR	BYTE[8]					' Holds 8 characters read from slave



        ADCON1 = 7					' Set PORTA and PORTE to digital
        Low PORTE.2					' LCD R/W line low (W)
        Pause 100					' Wait for LCD to start up

        LCDOut $fe, 1, "I2CX"		' Display
		Pause 1000


loop:
        I2CWrite SDA,SCL,$02,[127], bogus	' Write offset to slave
        Pause 500               


        I2CRead SDA,SCL,$02,[STR a\8], bogus	' Read string from slave
        

        LCDOut $fe, 1, STR a\5,SDEC a[5]	' Display result, preceded by 5 character
        									' string received from slave.
        
        Pause 500

        GoTo loop					' Do it forever


bogus:
		LCDOut $fe,1, "timed out"	' I2C command timed out
		Pause 1000

		GoTo loop

        End
